<template>
  <el-card>
    <el-form :inline="true">
      <el-form-item label="一级分类" >
        <el-select  placeholder="请选择一级分类" :modelValue="category.category1Id" @update:modelValue="category1IdChange">
          <!-- <el-option v-for="c1 in category.category1List "  :key="c1.id" :label="c1.name" :value="c1.id"></el-option> -->
          <el-option v-for="c1 in category.category1List" :key="c1.id" :label="c1.name" :value="c1.id"></el-option>
          
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择二级分类" :modelValue="category.category2Id" @update:modelValue="category2IdChange" >
          <el-option v-for="c2 in category.category2List" :key="c2.id" :label="c2.name" :value="c2.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择三级分类" v-model="category.category3Id" >
          <el-option v-for="c3 in category.category3List" :key="c3.id" :label="c3.name" :value="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelecte",
};
</script>

<script lang="ts" setup>
// import CategorySelector from "@/components/CategorySelector/index.vue"
import { getCategory1ListApi,getCategory2ListApi,getCategory3ListApi} from "@/api/product/category";
import {onMounted,ref,reactive} from "vue"
// import type {CategoryList}  from "@/api/product/model/categoryModel"
import type { Category } from "./model";

const category = reactive<Category>({ 
  category1Id: undefined, // 初始化为undefined，为了一上来select显示请选择xxx文字
  category2Id: undefined,
  category3Id: undefined,
  category1List: [],
  category2List: [],
  category3List: [],
});
// const category1List = ref<CategoryList>()
// 收集一级分类数据
onMounted(async () => {
  category.category1List= await getCategory1ListApi();
});
// 当一级分类id发送变化触发的函数
const category1IdChange = async (category1Id: number) => {
  // 请求二级分类列表
  category.category2List = await getCategory2ListApi(category1Id);
  // 更新一级分类id
  category.category1Id = category1Id;
  // 让二级/三级分类不选中
  category.category2Id = undefined;
  category.category3Id = undefined;
  // 清空三级分类列表
  category.category3List = [];
};

// 当二级分类id发送变化触发的函数
const category2IdChange = async (category2Id: number) => {
  // 请求三级分类列表
  category.category3List = await getCategory3ListApi(category2Id);
  // 更新二级分类id
  category.category2Id = category2Id;
  category.category3Id = undefined;
};

</script>

<style scoped></style>

<style>
.el-form-item {
  margin: 10px 0;
}
</style>